package com.araaya.eslimsmobile.util;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.util.Log;

import com.araaya.eslimsmobile.ElandMobileHome;
import com.araaya.eslimsmobile.db.DatabaseFunction;
import com.araaya.eslimsmobile.db.GPSLand;

public class KmlParser {
	
	private DocumentBuilder dBuilder;
	private Document doc;
	private GPSLand land;
	private DatabaseFunction dbf;
	private DocumentBuilderFactory dbFactory;
	
	public boolean parseKmlToDatabase(File fXmlFile, Context context){
	
	dbFactory = DocumentBuilderFactory.newInstance();

	try {
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(fXmlFile);
	} catch (Exception e) {
		return false;
	}
	
	doc.getDocumentElement().normalize();
 
	land = new GPSLand();
	
	//land.setLandName(doc.getElementsByTagName("name").item(0).getTextContent());
	
	land.setLandName(fXmlFile.getName());
	
	NodeList coordList =  doc.getElementsByTagName("coordinates");
	land.setCoordinates(coordList.item(0).getTextContent());
	
	String[] midPointCoords = coordList.item(1).getTextContent().split(",");
	land.setLongitude(midPointCoords[0]);
	land.setLatitude(midPointCoords[1]);
	land.setAltitude(midPointCoords[2]);
	
	if(dbf==null){
		dbf = new DatabaseFunction(context);
	}
	
	long l = dbf.addGPSLand(land);
	
	if (l != -1) {
		return true;
	} else {
		return false;
	}
	}
}
